package com.bitcola.security.admin.biz;

import com.bitcola.security.admin.entity.User;
import com.bitcola.security.admin.feign.IDataServiceFeign;
import com.bitcola.security.admin.mapper.ColaChainMapper;
import com.bitcola.security.admin.mapper.ColaWithdrawMapper;
import com.bitcola.security.admin.mapper.UserBalanceChangeMapper;
import com.bitcola.security.admin.mapper.UserMapper;
import com.bitcola.security.auth.client.i18n.ColaLanguage;
import com.bitcola.security.auth.common.util.EncoderUtil;
import com.bitcola.security.common.constant.BalanceTypeConstants;
import com.bitcola.security.common.constant.FinancialConstant;
import com.bitcola.security.common.context.BaseContextHandler;
import com.bitcola.security.common.msg.AppResponse;
import com.bitcola.security.common.msg.TableResultResponse;
import com.bitcola.security.common.util.AdminQuery;
import com.bitcola.security.common.util.Snowflake;
import com.bitcola.entity.BalanceChange;
import com.bitcola.entity.ColaMeBalance;
import com.bitcola.entity.ColaMeBalanceWithdrawin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author wx
 * @create 2018-12-18 15:47
 **/
@Service
public class ColaWithdrawBiz {

    @Autowired
    ColaWithdrawMapper mapper;

    @Autowired
    IDataServiceFeign dataServiceFeign;


    @Autowired
    UserMapper userMapper;

    @Autowired
    UserBalanceChangeMapper balanceChangeMapper;

    Snowflake snowflake = new Snowflake();

    public TableResultResponse list(AdminQuery query) {
        List<ColaMeBalanceWithdrawin> list = mapper.list(query);
        Long total = mapper.total(query);
        return new TableResultResponse(total, list);
    }

    public Map<String, Object> info(String orderId) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> item = mapper.item(orderId);
        map.put("info", item);
        List<Map<String, Object>> inOut = mapper.inOut(item.get("user_id").toString());
        List<Map<String, Object>> deposit = new ArrayList<>();
        List<Map<String, Object>> withdraw = new ArrayList<>();
        for (Map<String, Object> m : inOut) {
            String type = m.get("type").toString();
            //String coinCode = m.get("coin_code").toString();
            //BigDecimal number = new BigDecimal(m.get("total").toString());
            if ("Deposit".equals(type)) {
                deposit.add(m);
            } else {
                withdraw.add(m);
            }
        }
        Map<String, Object> assets = new HashMap<>();
        assets.put("deposit", deposit);
        assets.put("withdraw", withdraw);
        map.put("assets", assets);
        return map;
    }

    @Transactional
    public int refuse(String orderId, String userId, String reason) {
        // 将冻结资金解冻
        BigDecimal number = mapper.withdrawNumber(orderId);
        String coinCode = mapper.withdrawCoinCode(orderId);
        boolean b = dataServiceFeign.transformBalance(userId, userId, coinCode, false,
                false, number, "", "");
        if (b) {
            return mapper.withdrawRefuse(orderId, reason, EncoderUtil.WITHDRAW_KEY);
        } else {
            return 0;
        }
    }

    @Autowired
    ColaChainMapper chainMapper;
    public void updateStatus(String orderId, String status, String reason) {
        mapper.updateStatus(orderId, status, reason, EncoderUtil.WITHDRAW_KEY);
    }

    public Map<String, String> orderWithdrawInfo(String orderId) {
        return mapper.orderWithdrawInfo(orderId);
    }

    @Transactional
    public void withdrawSuccessByChain(String id, String hash, String userId, BigDecimal number, String coinCode) {
        // 修改订单状态为成功,
        mapper.updateWithdrawStatus(id, hash);
        // 修改用户资金
        mapper.updateWithdrawUserBalance(userId + coinCode, number, EncoderUtil.BALANCE_KEY);
    }


    @Transactional
    public void depositeSuccess(String orderId)
    {
        int j = chainMapper.completeDepositStatus(orderId);
        if (j == 1){
            Map<String,Object> one = chainMapper.selectById(orderId);
            BigDecimal number = new BigDecimal(one.get("number").toString());
            String userId = one.get("user_id").toString();
            String coinCode = one.get("coin_code").toString();
            int i = chainMapper.completeDeposit(userId,coinCode,number,EncoderUtil.BALANCE_KEY);
            if (i == 0) throw new RuntimeException("用户资金出错:"+userId+" 币种: "+coinCode+" orderId:"+orderId);
//            ColaUserEntity info = userBiz.info(userId);
//            if (StringUtils.isNotBlank(info.getTelPhone())){
////                pushFeign.depositSuccessSms(info.getAreaCode(),info.getTelPhone(),coinCode,number.stripTrailingZeros().toPlainString());
//            } else {
////                pushFeign.depositSuccessEmail(info.getEmail(),coinCode,number.stripTrailingZeros().toPlainString(),info.getLanguage(),info.getAntiPhishingCode());
//            }
        }
    }

    @Transactional
    public AppResponse withdrawRecharge(Map<String, String> params) {
        String userId = params.get("userId");
        String strNumber = params.get("number");
        Assert.notNull(strNumber, "number 不能为空");
        Double number = Double.parseDouble(strNumber);
        String coinCode = params.get("coinCode");
        Assert.notNull(userId, "userId 不能为空");
        Assert.notNull(coinCode, "coinCode 不能为空");
        String operationId = BaseContextHandler.getUserID();
        User operateUser = userMapper.selectByPrimaryKey(operationId);
        if (!"ADMIN".equals(operateUser.getType())) {
            return AppResponse.error(ColaLanguage.get(ColaLanguage.FORBIDDEN));
        }
        if (number < 0 && number > 100000) {
            return AppResponse.error("输入错误");
        }
        BalanceChange balanceChange = new BalanceChange();
        balanceChange.setId(snowflake.nextIdStr());
        balanceChange.setUserId(userId);
        balanceChange.setSource(BalanceTypeConstants.BALANCE);
        balanceChange.setAmount(BigDecimal.valueOf(number));
//        balanceChange.setDescription();
        balanceChange.setCreateTime(new Date());
        balanceChange.setType(FinancialConstant.SYSTEM_REWARD);
        balanceChange.setCoinCode(coinCode);
        balanceChangeMapper.insertSelective(balanceChange);
        mapper.withdrawRecharge(userId + coinCode, BigDecimal.valueOf(number), EncoderUtil.BALANCE_KEY);
        return AppResponse.ok();
    }

    @Transactional
    public AppResponse increaseIncentives(Map<String, String> params) {
        String userId = params.get("userId");
        String strNumber = params.get("number");
        Assert.notNull(strNumber, "number 不能为空");
        Double number = Double.parseDouble(strNumber);
        String coinCode = params.get("coinCode");
        Assert.notNull(userId, "userId 不能为空");
        Assert.notNull(coinCode, "coinCode 不能为空");
        String operationId = BaseContextHandler.getUserID();
        User operateUser = userMapper.selectByPrimaryKey(operationId);
        if (!"ADMIN".equals(operateUser.getType())) {
            return AppResponse.error(ColaLanguage.get(ColaLanguage.FORBIDDEN));
        }
        if (number < 0 && number > 10000) {
            return AppResponse.error("输入错误");
        }
        ColaMeBalance colaMeBalance = mapper.selectByPrimaryKey(userId + coinCode);
        Assert.notNull(colaMeBalance,"账户信息不能为空");
        mapper.increaseIncentives(userId + coinCode,BigDecimal.valueOf(number));
        return AppResponse.ok();
    }
}
